﻿using Common.Utility;
using Newtonsoft.Json;
using System.Text;

namespace Common.Extensions
{
    public static class HttpExtensions
    {
        private static readonly JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        };

        public static async Task<HttpBaseResponse<T>> HttpPost<T>(this HttpClient client, string url, Dictionary<string, string>? headers = null, object? body = null) where T : class
        {
            var result = "";
            try
            {
                if (headers == null)
                {
                    headers = new Dictionary<string, string>();
                }
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Post,
                    RequestUri = new Uri(url),
                    Content = body == null ? null : new StringContent(JsonConvert.SerializeObject(body, jsonSerializerSettings), Encoding.UTF8, "application/json")
                };

                foreach (var header in headers)
                {
                    // 优先尝试添加到请求头
                    if (!request.Headers.TryAddWithoutValidation(header.Key, header.Value))
                    {
                        // 若失败，尝试添加到内容头（如 Content-Type）
                        request.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    }
                }
                var response = await client.SendAsync(request);
                string responseString = await response.Content.ReadAsStringAsync();
                result = responseString;
                if (response.IsSuccessStatusCode)
                {
                    return new HttpBaseResponse<T> { Code = 0, Msg = "成功", Data = JsonConvert.DeserializeObject<T>(responseString) };
                }
                else
                {
                    return new HttpBaseResponse<T> { Code = -1, Msg = "接口请求失败", Data = default(T) };
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"Request:{url}, Response:{result}", ex);
            }
            finally
            {
                LogHelper.Info($"Request:{url}, Response:{result}");
            }
            return new HttpBaseResponse<T> { Code = -1, Msg = "接口错误", Data = default(T) };
        }

        public static async Task<HttpBaseResponse<T>> HttpGet<T>(this HttpClient client, string url, Dictionary<string, string>? headers = null) where T : class
        {
            var result = "";
            try
            {
                if (headers == null)
                {
                    headers = new Dictionary<string, string>();
                }
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Get,
                    RequestUri = new Uri(url),
                };

                foreach (var header in headers)
                {
                    // 优先尝试添加到请求头
                    if (!request.Headers.TryAddWithoutValidation(header.Key, header.Value))
                    {
                        // 若失败，尝试添加到内容头（如 Content-Type）
                        request.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    }
                }
                var response = await client.SendAsync(request);
                string responseString = await response.Content.ReadAsStringAsync();
                result = responseString;
                if (response.IsSuccessStatusCode)
                {
                    return new HttpBaseResponse<T> { Code = 0, Msg = "成功", Data = JsonConvert.DeserializeObject<T>(responseString) };
                }
                else
                {
                    return new HttpBaseResponse<T> { Code = -1, Msg = "接口请求失败", Data = default(T) };
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"Request:{url}, Response:{result}", ex);
            }
            finally
            {
                LogHelper.Info($"Request:{url}, Response:{result}");
            }
            return new HttpBaseResponse<T> { Code = -1, Msg = "接口错误", Data = default(T) };
        }
    }

    public class HttpBaseResponse<T>
    {
        public bool IsSuccess { get { return Code == 0; } }
        public int Code { get; set; }
        public string Msg { get; set; }
        public T Data { get; set; }
    }
}
